"""GPT 服务管理模块"""
import threading
import os
from datetime import datetime
from config.settings import Config


class GPTService:
    """GPT 服务管理类"""
    
    def __init__(self):
        self.threads = []
    
    def _log_error(self, model_name, error_message):
        """
        记录错误日志到文件
        
        Args:
            model_name: 模型名称
            error_message: 错误信息
        """
        try:
            # 确保 files 目录存在
            os.makedirs(os.path.dirname(Config.ERROR_LOG_FILE), exist_ok=True)
            
            # 生成日志内容
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            log_entry = f"[{timestamp}] [{model_name}] {error_message}\n"
            
            # 追加写入日志文件
            with open(Config.ERROR_LOG_FILE, 'a', encoding='utf-8') as f:
                f.write(log_entry)
        except Exception as e:
            # 如果日志写入失败，也不影响程序运行
            pass
    
    def _safe_call_gpt(self, gpt_func, *args):
        """
        安全调用 GPT 函数，捕获异常避免影响其他模型
        
        Args:
            gpt_func: GPT 函数
            *args: 函数参数
        """
        try:
            gpt_func(*args)
        except Exception as e:
            # 如果出错，记录到日志文件，不输出到控制台
            model_name = gpt_func.__module__.split('.')[-1] if hasattr(gpt_func, '__module__') else '未知模型'
            self._log_error(model_name, str(e))
    
    def query_all(self, login_data, question):
        """
        并发查询所有配置的 GPT 服务
        
        Args:
            login_data: 登录数据，包含各个 GPT 服务的配置
            question: 要查询的问题
        """
        self.threads = []
        user_data = login_data['data']
        
        # 从配置文件读取用户选择的模型列表
        config = Config.load_config()
        enabled_models = config.get('模型', {}).get('模型', [])
        
        # 模型映射：配置中的简称 -> 实际处理逻辑
        model_handlers = {
            'AL': self._add_al_thread,
            'BD': self._add_bd_thread,
            'HS': self._add_hs_thread,
            'TX': self._add_tx_thread,
            'XF': self._add_xf_thread,
            'DP': self._add_dp_thread,
        }
        
        # 根据用户配置的模型列表动态添加线程
        for model_code in enabled_models:
            handler = model_handlers.get(model_code)
            if handler:
                handler(user_data, question)
        
        # 启动所有线程
        for t in self.threads:
            t.start()
        
        # 等待所有线程完成
        for t in self.threads:
            t.join()
    
    def _add_bd_thread(self, user_data, question):
        """添加百度文心一言线程"""
        if user_data.get('bdApiKey'):
            from common.gpt import GPT_BD
            try:
                bd_url = GPT_BD.get_token(user_data['bdApiKey'], user_data['bdSecretKey'])
                bd = threading.Thread(
                    target=self._safe_call_gpt,
                    args=(GPT_BD.get_answer, bd_url, question)
                )
                self.threads.append(bd)
            except Exception as e:
                self._log_error('百度文心一言', f'初始化失败: {str(e)}')
    
    def _add_xf_thread(self, user_data, question):
        """添加讯飞星火线程"""
        if user_data.get('xfAppId'):
            try:
                from common.gpt import GPT_XF
                xf = threading.Thread(
                    target=self._safe_call_gpt,
                    args=(GPT_XF.get_answer, user_data['xfAppId'], user_data['xfApiSecret'], user_data['xfApiKey'], question)
                )
                self.threads.append(xf)
            except Exception as e:
                self._log_error('讯飞星火', f'初始化失败: {str(e)}')
    
    def _add_hs_thread(self, user_data, question):
        """添加火山豆包线程"""
        if user_data.get('hsApiKey'):
            try:
                from common.gpt import GPT_HS
                hs = threading.Thread(
                    target=self._safe_call_gpt,
                    args=(GPT_HS.get_answer, user_data['hsApiKey'], user_data['hsModel'], question)
                )
                self.threads.append(hs)
            except Exception as e:
                self._log_error('火山豆包', f'初始化失败: {str(e)}')
    
    def _add_tx_thread(self, user_data, question):
        """添加腾讯混元线程"""
        if user_data.get('txGptSecretId'):
            try:
                from common.gpt import GPT_TX
                tx = threading.Thread(
                    target=self._safe_call_gpt,
                    args=(GPT_TX.get_answer, user_data['txGptSecretId'], user_data['txGptSecretKey'], user_data['txGptModel'], user_data['txAddress'], question)
                )
                self.threads.append(tx)
            except Exception as e:
                self._log_error('腾讯混元', f'初始化失败: {str(e)}')
    
    def _add_al_thread(self, user_data, question):
        """添加阿里通义千问线程"""
        if user_data.get('alApiKey'):
            try:
                from common.gpt import GPT_AL
                al = threading.Thread(
                    target=self._safe_call_gpt,
                    args=(GPT_AL.get_answer, user_data['alApiKey'], question)
                )
                self.threads.append(al)
            except Exception as e:
                self._log_error('阿里通义千问', f'初始化失败: {str(e)}')
    
    def _add_dp_thread(self, user_data, question):
        """添加 DeepSeek 线程"""
        if user_data.get('dpApiKey'):
            try:
                from common.gpt import GPT_DP
                dp = threading.Thread(
                    target=self._safe_call_gpt,
                    args=(GPT_DP.get_answer, user_data['dpApiKey'], question)
                )
                self.threads.append(dp)
            except Exception as e:
                self._log_error('DeepSeek', f'初始化失败: {str(e)}')
